/**
  ******************************************************************************
  * @file    SCK_TxData.c
  * @author  exatron
  * @version V1.0.0
  * @date    segunda, 22 de dezembro de 2014
  * @brief   Função para enviar dados no socket.
  ******************************************************************************
  * @attention
  *
  *
  ******************************************************************************
  */

/** @addtogroup SCK
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include <common.h>

extern Socket_t sock[N_SOCKS];

/* External functions --------------------------------------------------------*/

/** @defgroup SCK_Functions
  * @{
  */

/**
  * @brief  Função para enviar dados no socket.
  * @param  SocketID_t: Socket a enviar
  * @param  int size: Tamanho do buffer a enviar
  * @retval Devolve pela serial Result_t
  */
void SCK_TxData(SocketID_t id, int size)
{
	#ifdef DEBUG
	debug_append("%s - %s", __FUNCTION__, "enter");
	#endif

	char temp_buf[USART_RX_LEN];

	/* Verifica se o socket esta aberto */
	if(sock[id].status == Status_SocketClosed)
	{
		aux_USART0_puts("%s=%d;%d\r\n", "SCK_TXD", id, Result_SocketClosed);
	}
	/* Verifica se há conexão */
	else if(sock[id].status != Status_SocketConnected)
	{
		aux_USART0_puts("%s=%d;%d\r\n", "SCK_TXD", id, Result_Desconnected);
	}
	/* Verifica se há dados a serem enviados */
	else if(sock[id].istx == IsWrite)
	{
		aux_USART0_puts("%s=%d;%d\r\n", "SCK_TXD", id, Result_OnWrite);
	}
	else
	{
		sock[id].istx = IsWrite;

		/* Coloca a msg no buffer de envio do socket */
		bzero(temp_buf, sizeof(temp_buf));
		aux_USART1_gets(temp_buf, size);

		if(sock[id].type == TCP_CLIENT || sock[id].type == TCP_SERVER)
		{
			send(sock[id].clifd, temp_buf, size, 0);
		}
		else if(sock[id].type == UDP_CLIENT)
		{
			sendto(sock[id].clifd, temp_buf, size, 0, (struct sockaddr *)&sock[id].seraddr,sizeof(struct sockaddr));
		}
		else if(sock[id].type == UDP_SERVER)
		{
			sendto(sock[id].serfd, temp_buf, size, 0,(struct sockaddr *)&sock[id].cliaddr,sizeof(struct sockaddr));
		}

		sock[id].istx = NoWrite;

		aux_USART0_puts("%s=%d;%d\r\n", "SCK_TXD", sock[id].ID, Result_Ok);
	}

	aux_SetBusy(FALSE);

	#ifdef DEBUG
	debug_append("%s - %s", __FUNCTION__, "exit");
	#endif
}

/**
  * @}
  */

/**
  * @}
  */


